//
//  CHWebView.swift
//  bridging_js
//
//  Created by cyptt on 2021/7/28.
//
import Foundation
import UIKit
import WebKit
import Toast_Swift
import SwiftyJSON
import CHAFNetwork
import CHSimpleUI
var jsCallBackName = ""



class CHWebView: WKWebView,WKUIDelegate,WKNavigationDelegate, WKScriptMessageHandler {
    var chwebdelegate:CHWebDelegate?
    var parentController:UIViewController?
    var webProBar:CHWebProBar = CHWebProBar.init();
    let chloading:CHLoading = CHLoading()
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        if message.name == ADD_LISTENER{
            print("----jscallbackname----",message.body)
            jsCallBackName = message.body as! String
        }
        else if message.name == TOAST_SHOW_CA {
            print("弹出toast")
            parentController!.view.makeToast((message.body as! String))
        }
        else if message.name  == ALERT_SHOW_CA{

           CHWebAlert.init(parentController: parentController!, resultStr: message.body as! String, webView: self)
        
        }else if message.name  == PRINT_CA{
            print("回调了," + (message.body as!  String) )
        }else if message.name == CLOSE_CURRENT_PAGE_CA{
            self.parentController?.navigationController?.popViewController(animated: true)
        }else if message.name == SHOW_NAV_CA {
            showNavCallbackSuceess(resultStr: message.body as! String)
        }else if message.name == Hide_NAV_CA{
            self.parentController?.navigationController?.setNavigationBarHidden(true, animated: true)
        }else if message.name == GET_DEVICE_INFO_CA{
            getDeviceInfo()
        } else if message.name == OPEN_ALBUM_CA {
            openAlbum()
        } else if message.name == OPEN_CAMERA_CA {
            openCarema()
        }else if message.name == OPEN_VIDEO_CA {
            openVideo()
        }else if message.name == PLAY_VIDEO_CA {
            self.playVideo(body: message.body as! String)
        }else if message.name == SCAN_QR_CODE_CA {
             scanQRCode()
        }else if message.name == OPEN_NATIVE_AC_CA{
            openNativeUI(result: message.body as! String)
        }else if message.name == OPEN_STORE_PAGE_CA{
            openStorePage(result: message.body as! String)
        }else if message.name == GET_NET_STATUS {
            getNetStatus()
        }else if message.name == GET_LOCATION_INFO_CA{
            getLocationInfo()
        }else if message.name == SAVE_CACHE_CA {
            saveCache(result: message.body as! String)
        }else if message.name == READ_CACHE_CA{
            readCache(result: message.body as! String)
        }else if message.name == REMOVE_CACHE_CA{
            removeCache(result: message.body as! String)
        }else if message.name == PROCESSBAR_FULL_INIT_CA{
            initProcessBar(result: message.body as! String)
        }else if message.name == PROCESSBAR_FULL_START_CA {
            startProcessBar(result: message.body as! String)
        }else if message.name == PROCESSBAR_FULL_STOP_CA{
            stopProcessBar()
        }
//        else if message.name == DUN_INIT_CA {
//            configDun(result: message.body as! String)
//        }else if message.name == DUN_ISREGISTER_CA {
//            isRegister()
//        }else if message.name == DUN_REGISTER_CA{
//            register()
//        }else if message.name == DUN_APPLY_CERT_CA {
//            applyCert(result: message.body as! String)
//        }else if message.name == DUN_P1_SING_CA{
//            p1Sign(result: message.body as! String)
//        }else if message.name == DUN_P7_SING_CA{
//            p7Sign(result: message.body as! String)
//        }else if message.name == DUN_CHANGE_PIN_CA{
//            changePin(result: message.body as! String)
//        }else if message.name == DUN_CHECK_PIN_CA{
//            checkPin(result: message.body as! String)
//        }else if message.name == DUN_GET_CERT_CA{
//            getCert()
//        }else if message.name == DUN_GET_CERT_INFO_CA{
//            getCertInfo()
//        }else if message.name == DUN_ENC_CERT_ENC_CA{
//            encCertEnc(result: message.body as! String)
//        }else if message.name == DUN_ENC_CERT_DEC_CA{
//            encCertDec(result: message.body as! String)
//        }else if message.name == DUN_SIGN_CERT_ENC_CA{
//             signCertEnc(result: message.body as! String)
//        }else if message.name == DUN_SIGN_CERT_DEC_CA{
//            signCertDec(result: message.body as! String)
//        }
        else if message.name == ACTION_SHEET_CA{
            actionSheet(result: message.body as! String)
        }else if message.name == REQUEST_NET_CA {
            requestNet(result: message.body as! String)
        }else if message.name == OPEN_FACE_SERVICE_CA{
            print(message.body)
            faceAuthStart(result:  message.body as! String)
            
        }else if message.name == OPEN_OCR_SERVICE_CA{
         
            orcStart(result: message.body as! String)
        }else if message.name == SHOW_LOADING_CA {
    
            showLoading(result:  message.body as! String)
            
        }else if message.name == HIDE_LOADING_CA{
     
            hideLoading()
            
        }else if message.name == PALY_FINISH_CA{
            
        }
        
        //成功回调手机盾
        
    }
    


    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(WKNavigationActionPolicy.allow)
    }
   

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
        print(error)
    }
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print(error)
    }

    

    override init(frame: CGRect, configuration: WKWebViewConfiguration) {
        super.init(frame: frame, configuration: configuration)
        setUI()
    }
  
    
 
  
    init(controller:UIViewController,frame:CGRect,configuration: WKWebViewConfiguration,webDelegate:CHWebDelegate? = nil){
        super.init(frame: frame, configuration: configuration)
        self.chwebdelegate = webDelegate
        parentController = controller
        setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI(){
        self.uiDelegate = self
        self.navigationDelegate = self
        
        //js给swift传值注册方法
      
//        let funArr:[String] = [TOAST_SHOW_CA,ALERT_SHOW_CA,PRINT_CA,ADD_LISTENER,CLOSE_CURRENT_PAGE_CA,SHOW_NAV_CA,Hide_NAV_CA,GET_DEVICE_INFO_CA,OPEN_ALBUM_CA,OPEN_CAMERA_CA,OPEN_VIDEO_CA,PLAY_VIDEO_CA,
//                               SCAN_QR_CODE_CA,OPEN_NATIVE_AC_CA,OPEN_STORE_PAGE_CA,GET_NET_STATUS,GET_LOCATION_INFO_CA,SAVE_CACHE_CA,READ_CACHE_CA,REMOVE_CACHE_CA,PROCESSBAR_FULL_INIT_CA,PROCESSBAR_FULL_START_CA,PROCESSBAR_FULL_STOP_CA,DUN_INIT_CA,DUN_REGISTER_CA,DUN_ISREGISTER_CA,DUN_APPLY_CERT_CA,
//                               DUN_P1_SING_CA,DUN_P7_SING_CA,DUN_CHANGE_PIN_CA,DUN_CHECK_PIN_CA,
//                               DUN_GET_CERT_CA,DUN_GET_CERT_INFO_CA,DUN_ENC_CERT_ENC_CA,DUN_ENC_CERT_DEC_CA,DUN_SIGN_CERT_ENC_CA,DUN_SIGN_CERT_DEC_CA,
//                               ACTION_SHEET_CA,REQUEST_NET_CA,OPEN_OCR_SERVICE_CA,OPEN_FACE_SERVICE_CA,SHOW_LOADING_CA,HIDE_LOADING_CA
//
//        ]
//
//        for item in funArr {
//            self.configuration.userContentController.add(self,name: item)
//        }

        let funArr:[String] = [TOAST_SHOW_CA,ALERT_SHOW_CA,PRINT_CA,ADD_LISTENER,CLOSE_CURRENT_PAGE_CA,SHOW_NAV_CA,Hide_NAV_CA,GET_DEVICE_INFO_CA,OPEN_ALBUM_CA,OPEN_CAMERA_CA,OPEN_VIDEO_CA,PLAY_VIDEO_CA,
                               SCAN_QR_CODE_CA,OPEN_NATIVE_AC_CA,OPEN_STORE_PAGE_CA,GET_NET_STATUS,GET_LOCATION_INFO_CA,SAVE_CACHE_CA,READ_CACHE_CA,REMOVE_CACHE_CA,PROCESSBAR_FULL_INIT_CA,PROCESSBAR_FULL_START_CA,PROCESSBAR_FULL_STOP_CA,
                               ACTION_SHEET_CA,REQUEST_NET_CA,OPEN_OCR_SERVICE_CA,OPEN_FACE_SERVICE_CA,SHOW_LOADING_CA,HIDE_LOADING_CA,PALY_FINISH_CA

        ]
     
        for item in funArr {
            self.configuration.userContentController.add(self,name: item)
        }
        
        //注册手机盾

    }
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        
    }
    
}
//手机盾
extension CHWebView{
    
   
    func showLoading(result:String){
        var baseModelM:CHWebBaseModel<CHCommonModel>?
        if let baseModel = CHWebBaseModel<CHCommonModel>.deserialize(from: result ){
            
            baseModelM = baseModel
    
        }
        
        let model = baseModelM?.body!
        if model!.msg != nil{
            chloading.show(msg: model!.msg!)
        }else {
            chloading.show(msg: "")
        }
  
      
    
    }
    func hideLoading(){
        chloading.hide()
    }
    
    
    func faceAuthStart(result:String){
        
    
        var baseModelM:CHWebBaseModel<CHWebAuthInfoModel>?
        
        if let baseModel = CHWebBaseModel<CHWebAuthInfoModel>.deserialize(from: result ){
            
            baseModelM = baseModel
      
        }
        var cardTypeModel:CHWebAuthInfoModel? = baseModelM?.body
        
        let realName:String? = cardTypeModel?.name;
        let cardId:String? = cardTypeModel?.cardId;
        if cardTypeModel == nil{
            CHWebCommon.sendJsResultContent(webView: self, responseObject:"数据不能为空", callbackActiveName: C_OPEN_FACE_SERVICE_CA, isSucess: false);
            
            return
        }
      
        if realName == nil{
            CHWebCommon.sendJsResultContent(webView: self, responseObject:"姓名不能为空", callbackActiveName: C_OPEN_FACE_SERVICE_CA, isSucess: false);
            return
        }
        
        if cardId == nil{
            CHWebCommon.sendJsResultContent(webView: self, responseObject:"身份证号不能为空", callbackActiveName: C_OPEN_FACE_SERVICE_CA, isSucess: false);
            return
        }
      
     
                
    }
    func orcStart(result:String) {
     
        var baseModelM:CHWebBaseModel<CHWebOcrCardType>?
        
        if let baseModel = CHWebBaseModel<CHWebOcrCardType>.deserialize(from: result ){
            
            baseModelM = baseModel
    
        }
        let cardTypeModel = baseModelM!.body!
        let cardTypeSide:String = cardTypeModel.cardType!;
   
    
    }
    func requestNet(result:String){
        var baseModelM:CHWebBaseModel<WebNetModel>?
        
        if let baseModel = CHWebBaseModel<WebNetModel>.deserialize(from: result ){
            
            baseModelM = baseModel
        }
        let netModel = baseModelM!.body!;
        let url:String = netModel.url!
        let param:Dictionary = netModel.params!
        let method =  netModel.method!;
       
        
        let headers:Dictionary? = netModel.headers

        if method == "POST" {
            
            
            CHNetManage.POSTWithHeaders(url: url, param: param, headerDic:headers ) { (ressultResponse:Dictionary) in
                print("-----last---result",ressultResponse)
                CHWebCommon.sendJsResultContent(webView: self, responseObject:ressultResponse, callbackActiveName: C_REQUEST_NET_CA, isSucess: true);
            } failure: { (err) in
                print(err)
                CHWebCommon.sendJsResultContent(webView: self, responseObject:"连接服务器错误", callbackActiveName: C_REQUEST_NET_CA, isSucess: false);
            }
        }else{
            CHNetManage.GETWithHeaders(url: url, param: param, headerDic:headers ) { (ressultResponse:Dictionary) in
                print("-----last---result",ressultResponse)
                CHWebCommon.sendJsResultContent(webView: self, responseObject:ressultResponse, callbackActiveName: C_REQUEST_NET_CA, isSucess: true);
            } failure: { (err) in
                print(err)
                CHWebCommon.sendJsResultContent(webView: self, responseObject:"连接服务器错误", callbackActiveName: C_REQUEST_NET_CA, isSucess: false);
            }
        }
    }
    func actionSheet(result:String) {
        var baseModelM:CHWebBaseModel<CHWebTitleModel>?
        
        if let baseModel = CHWebBaseModel<CHWebTitleModel>.deserialize(from: result ){
            
            baseModelM = baseModel
      
        }
        let webTitle:CHWebTitleModel? = baseModelM?.body!
        let titleStr:String? = webTitle!.title!;
        print(webTitle!.content!)
        CHDefaultAlert.show(with: self.parentController!, title: titleStr!, message: "", arr: webTitle!.content!) { (action:UIAlertAction) in
            print(action.title!)
            if(action.title! != "取消"){
                CHWebCommon.sendJsResultContent(webView: self, responseObject: action.title!, callbackActiveName: C_ACTION_SHEET_CA, isSucess: true);
            }else{
                CHWebCommon.sendJsResultContent(webView: self, responseObject: action.title!, callbackActiveName: C_ACTION_SHEET_CA, isSucess: false);
            }
           
        }
     
    }
//    /**
//     初始化手机盾
//     */
//    func configDun(result:String)  {
//        let webBaseM:CHWebBaseModel = getBaseModel(result: result)
//        print(webBaseM.body!)
//        let username:String = webBaseM.body! as! String
//        DunApi.sharedInstance().dunInit(username) { (result) in
//            print(result!)
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: result!, callbackActiveName: C_DUN_INIT_CA, isSucess: true);
//        } failB: { (err) in
//            print(err!)
//            
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_INIT_CA, isSucess: false);
//        }
//    }
//    
//    func isRegister()  {
//     
//        DunApi.sharedInstance().isRegisterSuccessB{ (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_ISREGISTER_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_ISREGISTER_CA, isSucess: false);
//        }
//    }
//    
//    
//    func register() {
//        
//        DunApi.sharedInstance().registerDunSuccessB { (success) in
//            print(success!)
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_REGISTER_CA, isSucess: true);
//        } failB: { (err) in
//            print(err!)
//            
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_REGISTER_CA, isSucess: false);
//        }
//
//    }
//    
//    func applyCert(result:String) {
//        print(result)
//        let webBaseM:CHWebBaseModel = getBaseModel(result: result)
//        print(webBaseM.body!)
//        let pin:String = webBaseM.body! as! String
//        DunApi.sharedInstance().applyCertPin(pin) { (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_APPLY_CERT_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_APPLY_CERT_CA, isSucess: false);
//        }
//    }
//    
//    func p1Sign(result:String) {
//       print(result)
//        var baseModelM:CHWebBaseModel<CHSignInfo>?
//        
//        if let baseModel = CHWebBaseModel<CHSignInfo>.deserialize(from: result ){
//            
//            baseModelM = baseModel
//      
//        }
//        let signInfo:CHSignInfo? = baseModelM?.body!
//        DunApi.sharedInstance().p1SignOri(signInfo!.signOri!, pin: signInfo!.pin!, isBase64: signInfo!.isBase64!) { (success) in
//            print(success!)
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_P1_SING_CA, isSucess: true);
//        } failB: { (err) in
//            print(err!)
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_P1_SING_CA, isSucess: false);
//        }
//
//    }
//    
//    func p7Sign(result:String){
//        var baseModelM:CHWebBaseModel<CHSignInfo>?
//        
//        if let baseModel = CHWebBaseModel<CHSignInfo>.deserialize(from: result ){
//            
//            baseModelM = baseModel
//      
//        }
//        let signInfo:CHSignInfo? = baseModelM?.body!
//        DunApi.sharedInstance().p7SignOri(signInfo!.signOri!, pin: signInfo!.pin!) { (success) in
//            print(success!)
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_P7_SING_CA, isSucess: true);
//        } failB: { (err) in
//            print(err!)
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_P7_SING_CA, isSucess: false);
//        }
//    }
//    
//    func changePin(result:String)  {
//        var baseModelM:CHWebBaseModel<CHWebPin>?
//        
//        if let baseModel = CHWebBaseModel<CHWebPin>.deserialize(from: result ){
//            
//            baseModelM = baseModel
//      
//        }
//        let pinInfo:CHWebPin? = baseModelM?.body!
//        
//        DunApi.sharedInstance().changeOldPin(pinInfo!.oldPin!, newPin: pinInfo!.newPin!) { (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_CHANGE_PIN_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_CHANGE_PIN_CA, isSucess: false);
//        }
//
//    }
//    
//    func checkPin(result:String) {
//        var baseModelM:CHWebBaseModel<CHWebPin>?
//        
//        if let baseModel = CHWebBaseModel<CHWebPin>.deserialize(from: result ){
//            
//            baseModelM = baseModel
//      
//        }
//        let pinInfo:CHWebPin? = baseModelM?.body!
//        DunApi.sharedInstance().checkPin(pinInfo!.oldPin!) { (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_CHECK_PIN_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_CHECK_PIN_CA, isSucess: false);
//        }
//
//    }
//    
//    func getCert(){
//        DunApi.sharedInstance().getCertSuccessB { (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_GET_CERT_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_GET_CERT_CA, isSucess: false);
//        }
//
//    }
//    
//    func getCertInfo(){
//        DunApi.sharedInstance().getCertInfoSuccessB { (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_GET_CERT_INFO_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_GET_CERT_INFO_CA, isSucess: false);
//        }
//
//    }
//    
//    func encCertEnc(result:String)  {
//        let webBaseM:CHWebBaseModel = getBaseModel(result: result)
//        print(webBaseM.body!)
//        let oriText:String = webBaseM.body! as! String
//        
//        DunApi.sharedInstance().encryptioncertEncryptionPlainTex(oriText) { (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_ENC_CERT_ENC_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_ENC_CERT_ENC_CA, isSucess: false);
//        }
//    }
//    func encCertDec(result:String){
//        var baseModelM:CHWebBaseModel<CHWebEncInfo>?
//        
//        if let baseModel = CHWebBaseModel<CHWebEncInfo>.deserialize(from: result ){
//            
//            baseModelM = baseModel
//      
//        }
//        let encInfo:CHWebEncInfo? = baseModelM?.body!
//        if encInfo?.encResult == nil {
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: "解密内容不能为空", callbackActiveName: C_DUN_ENC_CERT_DEC_CA, isSucess: false);
//            return
//        }
//        DunApi.sharedInstance().encryptionCertDecryptWithencResult(encInfo!.encResult!, pin: encInfo!.pin!) { (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_ENC_CERT_DEC_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_ENC_CERT_DEC_CA, isSucess: false);
//        }
//
//    }
//    
//    func signCertEnc(result:String){
//        let webBaseM:CHWebBaseModel = getBaseModel(result: result)
//        print(webBaseM.body!)
//        let oriText:String = webBaseM.body! as! String
//        DunApi.sharedInstance().signatureCertEncrytion(withPlainText: oriText) { (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_SIGN_CERT_ENC_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_SIGN_CERT_ENC_CA, isSucess: false);
//        }
//
//    }
//    
//    func signCertDec(result:String)  {
//        var baseModelM:CHWebBaseModel<CHWebEncInfo>?
//        
//        if let baseModel = CHWebBaseModel<CHWebEncInfo>.deserialize(from: result ){
//            
//            baseModelM = baseModel
//      
//        }
//        let encInfo:CHWebEncInfo? = baseModelM?.body!
//        
//        if encInfo?.signResult == nil {
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: "解密内容不能为空", callbackActiveName: C_DUN_SIGN_CERT_DEC_CA, isSucess: false);
//            return
//        }
//        
//        DunApi.sharedInstance().signatureCertDecrypt(withSignResult: encInfo!.signResult! , pin: encInfo!.pin!) { (success) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: success!, callbackActiveName: C_DUN_SIGN_CERT_DEC_CA, isSucess: true);
//        } failB: { (err) in
//            CHWebCommon.sendJsResultContent(webView: self, responseObject: err!, callbackActiveName: C_DUN_SIGN_CERT_DEC_CA, isSucess: false);
//        }
//
//    }
    
}

//成功
extension CHWebView{
    
 
    
    /**
     获取解析点数据
     */
    func getBaseModel(result:String) -> CHWebBaseModel<Any> {
        
        var baseModelM:CHWebBaseModel<Any>?
        
        if let baseModel = CHWebBaseModel<Any>.deserialize(from: result ){
            
            baseModelM = baseModel
      
        }
        return baseModelM!
    }
    
   
    /**
     初始化bar
     */
    
    func initProcessBar(result:String)  {
        
        webProBar.initBar(result: result)
     
    }
    
    /**
     开始进度条
     */
    func startProcessBar(result:String) {
        webProBar.startBar(result: result)
    }
    
    /**
     结束进度条
     */
    func stopProcessBar() {
        webProBar.stopBar()
    }
    
    /**
     移除缓存
     */
    func removeCache(result:String) {
        var baseModelM:CHWebBaseModel<CHWebCacheM>?
        if let baseModel = CHWebBaseModel<CHWebCacheM>.deserialize(from: result ){
            baseModelM = baseModel
        }
        let webChacheM:CHWebCacheM? = baseModelM?.body!
        let isValue =  UserDefaults.standard.object(forKey:webChacheM!.key!)
        
        if isValue == nil {
            CHWebCommon.sendJsResultContent(webView: self, responseObject:"失败,缓存不存在", callbackActiveName: C_REMOVE_CACHE_CA, isSucess: false)
        }else{
            UserDefaults.standard.removeObject(forKey:  webChacheM!.key!)
            CHWebCommon.sendJsResultContent(webView: self, responseObject:"成功", callbackActiveName: C_REMOVE_CACHE_CA, isSucess: true)
        }
    }
    
    /**
     缓存
     */
    func saveCache(result:String) {
    
        var baseModelM:CHWebBaseModel<CHWebCacheM>?
        
        if let baseModel = CHWebBaseModel<CHWebCacheM>.deserialize(from: result ){
            
            baseModelM = baseModel
      
        }
        
        let webChacheM:CHWebCacheM? = baseModelM?.body!
        print(webChacheM!.key!);
        print(webChacheM!.value!);
      
        if webChacheM != nil && webChacheM?.key != nil && webChacheM?.value != nil  {
      
            
            UserDefaults.standard.setValue(webChacheM!.value!, forKey: webChacheM!.key!)
            
            UserDefaults.standard.synchronize()
            CHWebCommon.sendJsResultContent(webView: self, responseObject:true, callbackActiveName: C_SAVE_CACHE_CA, isSucess: true)
        }else{
            CHWebCommon.sendJsResultContent(webView: self, responseObject:"失败", callbackActiveName: C_SAVE_CACHE_CA, isSucess: false)
        }
    
    }
    
    /**
     读取缓存
     */
    func readCache(result:String) {
        var baseModelM:CHWebBaseModel<CHWebCacheM>?
        
        if let baseModel = CHWebBaseModel<CHWebCacheM>.deserialize(from: result ){
            
            baseModelM = baseModel
        }
        
        let webChacheM:CHWebCacheM? = baseModelM?.body!
        
        if webChacheM != nil && webChacheM?.key != nil {

         
        
            let result2 = UserDefaults.standard.object(forKey: webChacheM!.key!)
            
            if(result2 == nil){
                CHWebCommon.sendJsResultContent(webView: self, responseObject:"读取失败", callbackActiveName: C_READ_CACHE_CA, isSucess: false)
            }else{
                CHWebCommon.sendJsResultContent(webView: self, responseObject:result2!, callbackActiveName: C_READ_CACHE_CA, isSucess: true)
            }
       
           
        }else{
            
            CHWebCommon.sendJsResultContent(webView: self, responseObject:"读取失败", callbackActiveName: C_READ_CACHE_CA, isSucess: false)
        }
        
      
    
    }
    /**
     获取位置信息
     */
    func getLocationInfo()  {
        let location:CHLocationManager = CHLocationManager.shared;
        location.startPositioning(self.parentController!)

        location.getLocationInfo { (resultDic) in
            print(resultDic)
            CHWebCommon.sendJsResultContent(webView: self, responseObject: resultDic, callbackActiveName: C_GET_LOCATION_INFO_CA, isSucess: true)

        } fail: { (err) in
            print(err)
        }
    }
    
    /**
     获取网络状态
     */
    func getNetStatus(){
     
        
        let net:CHReachability = CHReachability.init();
       
        net.checkNeatStatus { (netStatus:NetworkStatus) in
          
            if (netStatus == NotReachable){
                CHWebCommon.sendJsResultContent(webView: self, responseObject: "NONET", callbackActiveName: C_GET_NET_STATUS, isSucess: true)
            }else if(netStatus == ReachableViaWWAN){
                CHWebCommon.sendJsResultContent(webView: self, responseObject: "WAN", callbackActiveName: C_GET_NET_STATUS, isSucess: true)
            }else if(netStatus == ReachableViaWiFi){
                CHWebCommon.sendJsResultContent(webView: self, responseObject: "WIFI", callbackActiveName: C_GET_NET_STATUS, isSucess: true)
            }
          
        }
         
        
    }
    /**
     打开商店
     */
    func openStorePage(result:String){
        let baseModelM:CHWebBaseModel<Any>? = getBaseModel(result: result)
        
        let storeUrl:String = baseModelM?.body! as! String
        print(storeUrl)
        let url:URL? = URL.init(string: storeUrl) ;
        UIApplication.shared.open(url!, options:[:], completionHandler: nil);
    }

   
    /**
     打开原生界面
     */
    func openNativeUI(result:String){
    
        let baseModelM:CHWebBaseModel<Any>? = getBaseModel(result: result)
        
        let vcname:String = baseModelM?.body! as! String

        let workName = CHDeviceInfo.getProjectName()
        let className:String = "\(workName).\(vcname)";
     
        if NSClassFromString(className) != nil {
            let class_VC = NSClassFromString(className) as! UIViewController.Type

            let VC:UIViewController = class_VC.init()

            self.parentController?.navigationController?.pushViewController(VC, animated: true)
            
            CHWebCommon.sendJsResultContent(webView: self, responseObject: "打开成功", callbackActiveName: C_OPEN_NATIVE_AC_CA, isSucess: true)
        }else{
            
            CHWebCommon.sendJsResultContent(webView: self, responseObject: "找不到界面", callbackActiveName: C_OPEN_NATIVE_AC_CA, isSucess: false)
        }
    }
     
    /**
     扫码
     */
    func scanQRCode(){
        
        let VC:CHQRViewController = CHQRViewController.init();
        self.parentController?.navigationController?.pushViewController(VC, animated: true)
        
        VC.scanResult { (result) in
            print(result)
            
            self.parentController?.navigationController?.popViewController(animated: true)
            CHWebCommon.sendJsResultContent(webView: self, responseObject: result, callbackActiveName: C_SCAN_QR_CODE_CA, isSucess: true)
        }
       
        
        
    }
    /**
     显示导航栏回调成功
     */
    func showNavCallbackSuceess(resultStr:String)  {
        
        var commonStyleModel:CHCommonStyleModel?
        var comStyle:CHWebStyle?
        
       
        if let baseModel = CHWebBaseModel<CHCommonStyleModel>.deserialize(from: resultStr ){
            
        
            commonStyleModel = baseModel.body
            comStyle = commonStyleModel?.style

        }
        
        if ((comStyle?.bgColor) != nil) {
         
            self.parentController?.navigationController?.navigationBar.barTintColor = JSdkColor.init(hexString: (comStyle?.bgColor)!)
        }
        
        if ((commonStyleModel?.title) != nil) {
            self.parentController?.navigationItem.title = commonStyleModel?.title
        }
        
    
        if ((comStyle?.textColor) != nil) {
            self.parentController?.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:JSdkColor.init(hexString: (comStyle?.textColor)!)]
            
        }
        
        if ((comStyle?.textSize) != nil) {
        
            
            self.parentController?.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: CGFloat((comStyle?.textSize)!))]
        }
        if (comStyle?.textSize) != nil && (comStyle?.textColor) != nil {
            self.parentController?.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: CGFloat((comStyle?.textSize)!)),NSAttributedString.Key.foregroundColor:JSdkColor.init(hexString: (comStyle?.textColor)!)]
        }
        self.parentController?.navigationController?.setNavigationBarHidden(false, animated: true)
      
    }
    
    
    /**
     获取设备信息
     */
    func getDeviceInfo(){
        
        var dic:[String: Any] = [:]
        dic["appDisplayName"] = CHDeviceInfo.appDisplayName();
        dic["deviceModel"] = CHDevice().modelName
        dic["appVersion"] =  CHDeviceInfo.getAppVersion();
        dic["systemVersion"]  =      CHDeviceInfo.iosVersion();
        dic["deviceToken"] =  CHDeviceInfo.deviceToken();
        CHWebCommon.sendJsResultContent(webView: self, responseObject: dic, callbackActiveName: C_DEVICE_INFO, isSucess: true)
        
    }
    
    
    
    
    /**
     播放视频
     */
    func playVideo(body:String) {
        
        var baseModelM:CHWebBaseModel<String>?
        
        if let baseModel = CHWebBaseModel<String>.deserialize(from: body ){
            
            baseModelM = baseModel
      
        }
  
    }
    /**
     录制视频
     */
    func openVideo(){
        CHSysCamera.shared.openVideo(controller: self.parentController!) { (filePath) in
            print(filePath);
            let paraDic = ["filePath":filePath]
            CHWebCommon.sendJsResultContent(webView: self, responseObject: paraDic, callbackActiveName: C_OPEN_VIDEO_CA, isSucess: true)
        } failB: { (err) in
            print(err)
            
             CHWebCommon.sendJsResultContent(webView: self, responseObject: err, callbackActiveName: C_OPEN_VIDEO_CA, isSucess: false)
        }

    }
    
    /**
     打开相册
     */
    func openAlbum()  {
        CHSysCamera.shared.openAblum(controller: self.parentController!) { (image,fileUrl) in
            
            let base64 = CHStringTool.imageToBase64(image: image)
     
            //存储图片
           let imageName:String = String(CHStringTool.getNowTimeInterval()) + ".png"
          
       
           let filePath =  JSdkFileManage.saveImage(image: image, persent: 1, imageName:imageName );
         
            let paraDic = ["base64":base64,"filePath":filePath]
            CHWebCommon.sendJsResultContent(webView: self, responseObject: paraDic, callbackActiveName: C_OPEN_ALBUM_CA, isSucess: true)
        } failB: { (msg) in
            print(msg)
           
            CHWebCommon.sendJsResultContent(webView: self, responseObject: msg, callbackActiveName: C_OPEN_ALBUM_CA, isSucess: false)
        }
    }
    
    /**
     打开相机拍照
     */
    func openCarema()  {
        
    
        CHSysCamera.shared.openCamera(controller: self.parentController!) { (image,fileUrl) in
            let base64 = CHStringTool.imageToBase64(image: image)
     
            //存储图片
           let imageName:String = String(CHStringTool.getNowTimeInterval()) + ".png"
          
       
           let filePath =  JSdkFileManage.saveImage(image: image, persent: 1, imageName:imageName );
         
            let paraDic = ["base64":base64,"filePath":filePath]
            
            
            CHWebCommon.sendJsResultContent(webView: self, responseObject: paraDic, callbackActiveName: C_OPEN_CAMERA_CA, isSucess: true)
        } failB: { (msg) in
            print(msg)
            CHWebCommon.sendJsResultContent(webView: self, responseObject: msg, callbackActiveName: C_OPEN_CAMERA_CA, isSucess: false)
        }
         
    }
    
    
}
